import { api } from '../boot/axios'
import { StockItemImpWork } from './type'

function url(s: string) {
  if (s==''){
    return ['/api/stockitemimpwork', ''].join('/')
  }
  return ['/api/stockitemimpwork', s.replace('/', ''), ''].join('/')
}


export async function getStockItemImpWorks(stock_code:string){
  const res = await api({
    url: url('get_stock_item_imp_works'),
    method: 'post',
    data: {
      stock_code
    }
  })
  return res.data.data.filter((v: StockItemImpWork)=>v.invalid==0) as StockItemImpWork[]
}

export async function getStockItemImpWork(id:number){
  const res = await api({
    url: url('')+`${id}`,
    method: 'get',
  })
  return res.data as StockItemImpWork
}

export async function patchStockItemImpWork(id:number,data:any={},file:File|null=null){
  
  const formData = new FormData();

  if (data.stock_code) {
      formData.append('stock_code', data.stock_code);
  }
  if (data.doc_name) {
    formData.append('doc_name', data.doc_name);
  }
  if (data.description) {
    formData.append('description', data.description);
  }
  if (data.version) {
    formData.append('version', data.version);
  }
  
  if (file) {
    formData.append('file', file);
  }

  const res = await api({
    url: url('')+`${id}/`,
    method: 'patch',
    data:formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return res.data as StockItemImpWork
}
export function createStockItemImpWorks(stock_code:string,doc_name:string,description:string,version:string,file:File|null){

  const formData = new FormData();

  formData.append('stock_code', stock_code);
  formData.append('doc_name', doc_name);
  formData.append('description', description);
  formData.append('version', version);

  if (file) {
    formData.append('file', file);
  }

  return api({
    url: url(''),
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
}

export function deleteStockItemImpWork(id:number){
  return api({
    url: url(`${id}`),
    method: 'delete',
  })
}